using System;
using System.Diagnostics;
using System.Threading;

namespace extend_360.utils
{
    public class CmdUtils
    {
        public static void ShutDown()
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("shutdown", "/s /t 5")
            {
                CreateNoWindow = true
            };
            System.Diagnostics.Process.Start(processStartInfo);
        }

        public static void Process(string cmd, int sleepTime)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", cmd)
            {
                CreateNoWindow = true
            };
            System.Diagnostics.Process.Start(processStartInfo);
            // 等待浏览器打开
            Thread.Sleep(sleepTime);
        }

        public static Process ProcessByPath(string path, int sleepTime)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo(path)
            {
                CreateNoWindow = true
            };
            Process process = System.Diagnostics.Process.Start(processStartInfo);
            // 等待软件窗体加载（根据实际情况调整等待时间）
            process?.WaitForInputIdle();
            Thread.Sleep(sleepTime);
            return process;
        }

        public static void KillProcess(Process[] process)
        {
            if (process != null)
            {
                foreach (var item in process)
                {
                    item.Kill(true);
                    SystemUtils.ConsoleWrite("进程关闭完成", ConsoleColor.Green);
                }
            }
        }

        /// <summary>
        /// 通过进程名称KILL进程
        /// </summary>
        /// <param name="applicationName"></param>
        public static void KillProcessByApplicationName(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
            {
                return;
            }
            Thread.Sleep(3000);
            string[] arrays = applicationName.Split("\\", StringSplitOptions.RemoveEmptyEntries);
            Process[] process = System.Diagnostics.Process.GetProcessesByName(arrays[arrays.Length - 1]?.Replace(".exe",""));
            KillProcess(process);
        }
    }
}